<template>
	<view class="content">
		<view class="row b-b">
			<text class="tit">联系人</text>
			<input class="input" type="text" v-model="addressData.name" placeholder="收货人姓名"
				placeholder-class="placeholder" />
		</view>
		<view class="row b-b">
			<text class="tit">手机号</text>
			<input class="input" type="number" v-model="addressData.mobile" placeholder="收货人手机号码"
				placeholder-class="placeholder" />
		</view>

		<view class="row b-b">
			<text class="tit">地区</text>
			<view class="address-display" @click="showRegionPicker">
				{{ selectedProvinceName }} {{ selectedCityName }} {{ selectedDistrictName }}
			</view>
		</view>

		<!-- 底部地区选择器 -->
		<view class="region-picker-wrapper" v-if="showPicker" @touchmove.stop.prevent>
			<view class="mask" @click="closePicker"></view>
			<view class="picker-content">
				<view class="picker-header">
					<text @click="closePicker">取消</text>
					<text class="title">请选择地区</text>
					<text @click="confirmRegion">确定</text>
				</view>

				<view class="columns-wrapper">
					<!-- 省份列 -->
					<scroll-view scroll-y class="column">
						<view v-for="province in provinces" :key="province.id"
							:class="['item', province.id === selectedProvince && 'active']"
							@click="selectProvince(province)">
							{{ province.name }}
						</view>
					</scroll-view>

					<!-- 城市列 -->
					<scroll-view scroll-y class="column" v-if="selectedProvince">
						<view v-for="city in cities" :key="city.id"
							:class="['item', city.id === selectedCity && 'active']" @click="selectCity(city)">
							{{ city.name }}
						</view>
					</scroll-view>

					<!-- 区县列 -->
					<scroll-view scroll-y class="column" v-if="selectedCity">
						<view v-for="district in districts" :key="district.id"
							:class="['item', district.id === selectedDistrict && 'active']"
							@click="selectDistrict(district)">
							{{ district.name }}
						</view>
					</scroll-view>
				</view>
			</view>
		</view>

		<view class="row b-b">
			<text class="tit">详细地址</text>
			<input class="input" type="text" v-model="addressData.address" placeholder-class="placeholder" />
			<!-- <text class="yticon icon-shouhuodizhi"></text> -->
		</view>
		
		<view class="row default-row">
		  <text class="tit">设为默认</text>
		  <view class="radio-group">
		    <radio :value="1" :checked="iDefault" @click="switchChange(addressData.isDefault)" color="#fa436a" />
		  </view>
		</view>
		<button class="add-btn" @click="confirm">提交</button>
	</view>
</template>

<style>
	/* 地区显示框 */
	.address-display {
		flex: 1;
		padding: 12px;
		border: 1px solid #eee;
		border-radius: 6px;
		min-height: 40px;
		line-height: 1.5;
	}

	.placeholder {
		color: #999;
	}

	/* 下拉菜单样式 */
	.dropdown-toggle {
		padding: 10px;
		border: 1px solid #ccc;
		border-radius: 4px;
		background-color: #fff;
	}

	.dropdown-menu {
		border: 1px solid #ccc;
		border-radius: 4px;
		background-color: #fff;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
	}

	.dropdown-item {
		padding: 8px 16px;
		cursor: pointer;
	}

	.dropdown-item:hover {
		background-color: #f5f5f5;
	}

	/* 弹窗样式（这里不再使用弹窗，但保留样式可用于后续扩展或备用） */
	.region-dialog .el-dialog__header {
		padding: 16px 20px;
		border-bottom: 1px solid #eee;
	}

	.region-dialog .el-dialog__body {
		padding: 0;
		max-height: 70vh;
	}

	/* 地区选项 */
	.region-item {
		padding: 14px 20px;
		border-bottom: 1px solid #f5f5f5;
		position: relative;
		font-size: 16px;
	}

	.icon-check {
		position: absolute;
		right: 20px;
		color: #409EFF;
	}

	/* 弹窗底部按钮 */
	.dialog-footer {
		padding: 16px;
		text-align: right;
		border-top: 1px solid #eee;
	}

	/* 滚动容器 */
	.dialog-scroll {
		height: 60vh;
	}
</style>


<script>
	import {
		getReProvinces,
		getReCities,
		getReDistricts,
		getAddressInsert,
		getAddressUpdate
	} from '@/config/api/address.js';
	import { mapState } from 'vuex';
	export default {
		computed: {
		    ...mapState(['userInfo'])
		  },
		data() {
			return {
				addressData: {
					id: 0,
					userId: 0,
					name: '',
					mobile: '',
					address: '',
					area: '',
					isDefault: 0,
					provinceId: 0,
					cityId: 0,
					areaId: 0
				},

				provinces: [],
				cities: [],
				districts: [],
				iDefault: false,
				selectedProvince: '',
				selectedCity: '',
				selectedDistrict: '',

				selectedProvinceName: '',
				selectedCityName: '',
				selectedDistrictName: '',

				showPicker: false,


			}
		},
		onLoad(option) {
			// console.log(option);
			let title = '新增收货地址';
			this.addressData.userId = this.userInfo.id;
			if (option.type === 'edit') {
				title = '编辑收货地址'
				this.addressData = JSON.parse(option.data)

				this.selectedProvinceName = this.addressData.provinceName.name
				this.selectedCityName = this.addressData.cityName.name
				this.selectedDistrictName = this.addressData.areaName.name

				this.selectedProvince = this.addressData.provinceId
				this.selectedCity = this.addressData.cityId
				if (this.addressData.isDefault == 0) {
					this.iDefault = false;
				} else if (this.addressData.isDefault == 1) {
					this.iDefault = true;
				}
			}
			this.manageType = option.type;
			uni.setNavigationBarTitle({
				title
			})
		},
		mounted() {
			if (this.selectedProvince != '') {
				this.loadRegions();
			}
		},
		methods: {
			switchChange(e) {
				// this.addressData.isDefault = e.detail;
				if (this.iDefault) {
					this.addressData.isDefault = 0;
					this.iDefault = !this.iDefault;
				} else {
					this.addressData.isDefault = 1;
					this.iDefault = !this.iDefault;
				}
				console.log(this.addressData.isDefault);
			},
			showRegionPicker() {
				this.showPicker = true;
				if (!this.provinces.length) this.getProvinces();
			},
			closePicker() {
				this.showPicker = false;
			},

			loadRegions() {
				this.getProvinces();
				this.getCities();
				this.getDistricts();
			},

			//获取行政区域省
			async getProvinces() {
				try {
					const res = await getReProvinces()
					if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code ===
						200) {
						this.provinces = res.data.data
						// console.log(JSON.stringify(this.provinces, null, 2));
					} else {
						console.error('请求失败:', res?.data?.msg || '未知错误');
					}
				} catch (error) {
					console.error('接口异常:', error)
					this.$message.error('数据加载失败')
				}
			},
			//获取行政区域市
			async getCities() {
				this.cities = [];
				this.selectedCity = '';
				this.districts = [];
				this.selectedDistrict = '';
				try {
					const res = await getReCities({
						provinceId: this.selectedProvince
					})
					if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code ===
						200) {
						this.cities = res.data.data
					} else {
						console.error('请求失败:', res?.data?.msg || '未知错误');
					}
				} catch (error) {
					console.error('接口异常:', error)
					this.$message.error('数据加载失败')
				}
			},
			//获取行政区域区
			async getDistricts() {
				this.districts = [];
				this.selectedDistrict = '';
				try {
					const res = await getReDistricts({
						cityId: this.addressData.cityId
					})
					if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code ===
						200) {
						this.districts = res.data.data
					} else {
						console.error('请求失败:', res?.data?.msg || '未知错误');
					}
				} catch (error) {
					console.error('接口异常:', error)
					this.$message.error('数据加载失败')
				}
			},

			// 选择省份
			selectProvince(province) {
				this.selectedProvince = province.id;
				this.selectedProvinceName = province.name;
				this.addressData.provinceId = province.id;
				this.getCities();
			},
			selectCity(city) {
				this.selectedCity = city.id;
				this.selectedCityName = city.name;
				this.addressData.cityId = city.id;
				this.getDistricts();
			},
			selectDistrict(district) {
				this.selectedDistrict = district.id;
				this.selectedDistrictName = district.name;
				this.addressData.areaId = district.id;
			},

			confirmRegion() {
				this.closePicker();
				// 更新地址数据
				this.addressData.province = this.selectedProvinceName;
				this.addressData.city = this.selectedCityName;
				this.addressData.district = this.selectedDistrictName;
			},
			confirmSelection() {
				this.isRegionSelectorVisible = false;
				// 这里可以添加数据提交逻辑
				const fullAddress = `${this.selectedProvinceName} ${this.selectedCityName} ${this.selectedDistrictName}`;
				console.log('选择的地址:', fullAddress);
			},




			//地图选择地址
			chooseLocation() {
				uni.chooseLocation({
					success: (data) => {
						this.addressData.addressName = data.name;
						this.addressData.address = data.name;
					}
				})
			},

			//提交
			async confirm() {
				let address = this.addressData;
				if (!address.name) {
					this.$api.msg('请填写收货人姓名');
					return;
				}
				if (!/(^1[3|4|5|7|8][0-9]{9}$)/.test(address.mobile)) {
					this.$api.msg('请输入正确的手机号码');
					return;
				}
				if (!address.address) {
					this.$api.msg('请在地图选择所在位置');
					return;
				}


				if (this.manageType == 'edit') {
					console.log(this.addressData.userId);
					const dtsaddress = {
						id: this.addressData.id,
						userId: this.addressData.userId,
						name: this.addressData.name,
						mobile: this.addressData.mobile,
						address: this.addressData.address,
						isDefault: this.addressData.isDefault,
						provinceId: this.addressData.provinceId,
						cityId: this.addressData.cityId,
						areaId: this.addressData.areaId
					}
					try {
						const res = await getAddressUpdate(dtsaddress)
						console.log('提交数据:', dtsaddress)
						uni.showToast({
							title: '提交成功',
							icon: 'success'
						})
						// 获取上一个页面实例
						const pages = getCurrentPages();
						const prevPage = pages[pages.length - 2];
						if (prevPage) {
							// 调用上一个页面的 loadAddress 方法刷新数据
							prevPage.$vm.loadAddress();
						}

						// 返回上一页
						uni.navigateBack({
							delta: 1
						});
					} catch (error) {
						console.error('接口异常:', error)
						// console.log('修改地址参数:', JSON.stringify(address, null, 2));
						this.$message.error(error.response?.data?.message || '提交失败')
					}
				} else {
					try {
						const res = await getAddressInsert(address)
						console.log('提交数据:', address)
						uni.showToast({
							title: '提交成功',
							icon: 'success'
						})
						// 获取上一个页面实例
						const pages = getCurrentPages();
						const prevPage = pages[pages.length - 2];
						if (prevPage) {
							// 调用上一个页面的 loadAddress 方法刷新数据
							prevPage.$vm.loadAddress();
						}

						// 返回上一页
						uni.navigateBack({
							delta: 1
						});
					} catch (error) {
						console.error('接口异常:', error)
						this.$message.error(error.response?.data?.message || '提交失败')
					}
				}



			},



		}
	}
</script>

<style lang="scss">
	.region-picker-wrapper {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 999;

		.mask {
			position: absolute;
			width: 100%;
			height: 100%;
			background: rgba(0, 0, 0, 0.5);
		}

		.picker-content {
			position: absolute;
			bottom: 0;
			left: 0;
			right: 0;
			background: #fff;
			border-radius: 20rpx 20rpx 0 0;
			padding: 20rpx 0;

			.picker-header {
				display: flex;
				justify-content: space-between;
				padding: 20rpx 30rpx;
				border-bottom: 1rpx solid #eee;

				text {
					color: #666;
					font-size: 32rpx;

					&.title {
						color: #333;
						font-weight: bold;
					}
				}
			}

			.columns-wrapper {
				display: flex;
				height: 500rpx;

				.column {
					flex: 1;
					height: 100%;

					.item {
						padding: 24rpx 30rpx;
						font-size: 28rpx;
						color: #666;

						&.active {
							color: #007AFF;
							background: #f5f5f5;
						}
					}
				}
			}
		}
	}

	page {
		background: $page-color-base;
		padding-top: 16upx;
	}

	.row {
		display: flex;
		align-items: center;
		position: relative;
		padding: 0 30upx;
		height: 110upx;
		background: #fff;

		.tit {
			flex-shrink: 0;
			width: 120upx;
			font-size: 30upx;
			color: $font-color-dark;
		}

		.input {
			flex: 1;
			font-size: 30upx;
			color: $font-color-dark;
		}

		.icon-shouhuodizhi {
			font-size: 36upx;
			color: $font-color-light;
		}
	}

	.default-row {
		margin-top: 16upx;

		.tit {
			flex: 1;
		}

		switch {
			transform: translateX(16upx) scale(.9);
		}
	}

	.add-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 690upx;
		height: 80upx;
		margin: 60upx auto;
		font-size: $font-lg;
		color: #fff;
		background-color: $base-color;
		border-radius: 10upx;
		box-shadow: 1px 2px 5px rgba(219, 63, 96, 0.4);
	}
</style>